﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace ParkService
{
    public class IniFiles
    {

        public string inipath;
        //声明API函数


        [DllImport("kernel32")]
        public static extern bool WritePrivateProfileString(byte[] section, byte[] key, byte[] val, string filePath);

        [DllImport("kernel32")]
        public static extern int GetPrivateProfileString(byte[] section, byte[] key, byte[] def, byte[] retVal, int size, string filePath);

        [DllImport("kernel32.dll")]
        private static extern int GetPrivateProfileSection(byte[] section, IntPtr lpReturnedString, uint nSize, string lpFileName);

        //与ini交互必须统一编码格式
        private static byte[] getBytes(string s, string encodingName)
        {
            return null == s ? null : Encoding.GetEncoding(encodingName).GetBytes(s);
        }

        /// <summary>
        /// 读取ini文件
        /// </summary>
        /// <param name="section"></param>
        /// <param name="key"></param>
        /// <param name="encodingName"></param>
        /// <param name="size"></param>
        /// <returns></returns>
        public string ReadString(string section, string key, string encodingName = "utf-8", int size = 1024)
        {
            byte[] buffer = new byte[size];
            int count = GetPrivateProfileString(getBytes(section, encodingName), getBytes(key, encodingName), getBytes("", encodingName), buffer, size, this.inipath);
            return Encoding.GetEncoding(encodingName).GetString(buffer, 0, count).Trim();
        }

        /// <summary>
        /// 读内容，不存在则写入一个默认值
        /// </summary>
        /// <param name="section"></param>
        /// <param name="key"></param>
        /// <param name="init_value"></param>
        /// <returns></returns>
        public string InitReadString(string section, string key, string init_value)
        {
            if (ExistINIFile())
            {
                string value = ReadString(section, key);
                if ((value.Length == 0) && (value.CompareTo(init_value) != 0))
                {
                    value = init_value;
                    WriteString(section, key, value);
                }
                return value;
            }
            else
            {
                WriteString(section, key, init_value);
                return init_value;
            }
        }

        /// <summary>
        /// 写入ini文件
        /// </summary>
        /// <param name="section"></param>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="encodingName"></param>
        /// <returns></returns>
        public bool WriteString(string section, string key, string value, string encodingName = "utf-8")
        {
            if (value == null)
            {
                return WritePrivateProfileString(getBytes(section, encodingName), getBytes(key, encodingName), null, this.inipath);
            }
            else
            {
                return WritePrivateProfileString(getBytes(section, encodingName), getBytes(key, encodingName), getBytes(value, encodingName), this.inipath);
            }

        }

        /// <summary>
        /// 根据section取所有key
        /// </summary>
        /// <param name="section"></param>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public string[] ReadIniAllKeys(string section, string encodingName = "utf-8")
        {
            UInt32 MAX_BUFFER = 32767;

            string[] items = new string[0];

            IntPtr pReturnedString = Marshal.AllocCoTaskMem((int)MAX_BUFFER * sizeof(char));

            int bytesReturned = GetPrivateProfileSection(getBytes(section, encodingName), pReturnedString, MAX_BUFFER, this.inipath);

            if (!(bytesReturned == MAX_BUFFER - 2) || (bytesReturned == 0))
            {
                byte[] buffer = new byte[bytesReturned];
                Marshal.Copy(pReturnedString, buffer, 0, bytesReturned);
                string returnedString = Encoding.GetEncoding(encodingName).GetString(buffer, 0, bytesReturned).Trim();
                items = returnedString.Split(new char[] { '\0' }, StringSplitOptions.RemoveEmptyEntries);
            }
            Marshal.FreeCoTaskMem(pReturnedString);

            return items;
        }

        /// <summary> 
        /// 构造方法 
        /// </summary> 
        /// <param name="INIPath">文件路径</param> 
        public IniFiles(string INIPath)
        {
            inipath = INIPath;
        }

        public IniFiles() { }

        /// <summary> 
        /// 验证文件是否存在 
        /// </summary> 
        /// <returns>布尔值</returns> 
        public bool ExistINIFile()
        {
            return File.Exists(inipath);
        }


    }
}
